package kr.saeildamil.androidstudy_second.gesture;

import java.util.ArrayList;

import kr.saeildamil.androidstudy_second.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.TextView;

public class TouchDump extends Activity {
	ArrayList<String> arTouch = new ArrayList<String>();
	TextView mResult;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch31_touchdump);
		
		mResult = (TextView)findViewById(R.id.ch31_touchdump_result);
		mResult.setText("멀티 터치를 테스트");
	}
	
	final static String[] arAction = {
		"DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE", "PDOWN", "PUP"};

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		int action = event.getAction();
		appendText(Integer.toString(action));
		int pureaction = action & MotionEvent.ACTION_MASK;
		int pid = (action & MotionEvent.ACTION_POINTER_ID_MASK)
				>>MotionEvent.ACTION_POINTER_INDEX_SHIFT;
		StringBuilder info = new StringBuilder();
		info.append("p" + pid + "" + arAction[pureaction]);
		
		for(int i=0; i<event.getPointerCount(); i++){
			info.append(String.format("p%d (%d, %d)", event.getPointerId(i), (int)event.getX(i), (int)event.getY(i)));
		}
		
		if(event.getPointerCount()>1){
			int dx = (int) (event.getX(0) - event.getX(1));
			int dy = (int) (event.getY(0) - event.getY(1));
			int distance = (int)(Math.sqrt(dx*dx + dy*dy));
			info.append("dis = " + distance);
		}
		
		appendText(info.toString());
		
		return super.onTouchEvent(event);
	}

	void appendText(String text){
		if(arTouch.size()>15){
			arTouch.remove(0);
		}
		arTouch.add(text);
		StringBuilder sb = new StringBuilder();
		for(String str:arTouch)	{
			sb.append(str + "\n");
		}
		mResult.setText(sb.toString());
    }
}